<template>
    <div class="dashboard-container">
        <div class="container">
            <!-- 按钮添加 -->
            <div class="tableBar">
                <el-input v-model="input" placeholder="请输入用户姓名" style="width: 250px" clearable
                          @keyup.enter.native="handleQuery">
                    <i slot="prefix" class="el-input__icon el-icon-search" style="cursor: pointer"></i>
                </el-input>
                <div class="tableLab" style="float: right;">
                    <el-link type="danger" @click="deleteHandle('批量', null)">批量删除</el-link>
                    <el-link type="primary" @click="statusHandle('1')">批量启用</el-link>
                    <el-link type="warning" @click="statusHandle('0')">批量禁用</el-link>
                    <el-button style="margin-left: 10px;" type="primary" @click="addMemberHandle()">
                        + 添加用户
                    </el-button>
                </div>
            </div>
        </div>

        <!-- el-table展示 -->
        <el-table v-loading="loading" :data="tableData" style="width: 100%" class="tableBox" border fit stripe
                  tooltip-effect="dark" :header-cell-class-name="'headerBg'"
                  @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" width="40px" style="border: none;"></el-table-column>
            <el-table-column align="center" label="注册时间" prop="createdTime" :formatter="formatDate" min-width="10%">
            </el-table-column>
            <el-table-column align="center" label="昵称" prop="nickname" min-width="10%"></el-table-column>
            <el-table-column align="center" label="用户名" prop="username" min-width="10%"></el-table-column>
            <el-table-column align="center" label="密码" prop="password" min-width="15%"></el-table-column>
            <el-table-column align="center" label="电话号码" prop="phoneNumber" min-width="10%"></el-table-column>

            <el-table-column align="center" label="用户权限" prop="role" min-width="10%">
                <template slot-scope="scope">
                    <el-tag type="primary" v-if="scope.row.role === 'user'">普通用户</el-tag>
                    <el-tag type="warning" v-if="scope.row.role === 'super'">超级用户</el-tag>
                    <!-- 					  <el-tag type="success" v-if="scope.row.role === 'ROLE_STUDENT'">学生</el-tag>
            {{ scope.row.role ==  ? '普通用户' : '超级用户'}} -->
                </template>
            </el-table-column>
            <el-table-column min-width="10%" align="center" label="头像">
                <template slot-scope="{ row }">
                    <el-image style=" border:none;cursor: pointer;width: 40px;height: 40px;border-radius: 50%;"
                              :src="`/gongyi/common/download?name=${row.avatar}`"
                              :preview-src-list="[ `/gongyi/common/download?name=${row.avatar}` ]">
                        <div slot="error" class="image-slot">
                            <i class="el-icon-picture-outline"></i>
                        </div>
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column min-width="7%" align="center" label="状态">
                <template slot-scope="scope">
                    <el-tag effect="dark" type="success" v-if="scope.row.status == '1'" round>正常</el-tag>
                    <el-tag effect="dark" type="danger" v-if="scope.row.status == '0'" round>已禁用</el-tag>
                    <!-- 					  <el-tag type="success" v-if="scope.row.role === 'ROLE_STUDENT'">学生</el-tag>
            {{ scope.row.role ==  ? '普通用户' : '超级用户'}} -->
                </template>
            </el-table-column>
<!--            <el-table-column align="center" label="允许发布活动" min-width="8%">
                <template slot-scope="scope">
                    <el-switch
                            v-model="scope.row.pub=='1'?true:false"
                            active-color="#55ff00"
                            inactive-color="#F56C6C"
                            @change="changePubStatus(scope.row)"
                    />
                </template>
            </el-table-column> -->
            <el-table-column label="操作" align="center" min-width="15%">
                <template slot-scope="scope">
                    <el-button type="text" style="color: #59DB61" size="midium" @click="handleRole(scope.row)">
                        {{ scope.row.role == 'user' ? '升权' : '降权'}}
                    </el-button>
                    <el-button type="text" size="midium" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="text" size="midium" @click="statusHandle(scope.row)">
                        {{ scope.row.status == '0' ? '启用' : '禁用' }}
                    </el-button>
                    <el-button type="text" size="midium" class="delBut common"
                               @click="deleteHandle('单删', scope.row.id)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 添加 -->
        <el-dialog title="用户信息" :visible.sync="dialogFormVisible">
            <div style="display: flex; algin-items:center; justify-content:center;">
                <el-form :model="user" :rules="rules" ref="userForm" :label-width="formLabelWidth" label-position="left"
                         style="width: 55%;" size="midium">
                    <el-form-item prop="username" label="用户名" autocomplete="off">
                        <el-input v-model="user.username" placeholder="请输入用户名" prefix-icon="el-icon-user"
                                  autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item prop="phoneNumber" label="电话号码" autocomplete="off">
                        <el-input v-model="user.phoneNumber" placeholder="请输入电话号码" prefix-icon="el-icon-mobile-phone
" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="头像:">

                        <el-upload class="avatar-uploader" action="/gongyi/common/upload" :show-file-list="true"
                                   :on-success="handleAvatarSuccess" :on-change="onChange" :before-remove="beforeRemove"
                                   :on-remove="handleRemove" :limit="1" :on-exceed="handleExceed" ref="upload"
                                   :file-list="fileList">
                            <img style="width: 100px; height: 100px" v-if="imageUrl" :src="imageUrl" class="avatar"
                                 fit="fit"></img>
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item prop="password" label="密码">
                        <el-input v-model="user.password" autocomplete="off" show-password placeholder="请输入密码"
                                  prefix-icon="el-icon-lock"></el-input>
                    </el-form-item>
                    <el-form-item prop="confirmPassword" label="确认密码">
                        <el-input v-model="user.confirmPassword" autocomplete="off" placeholder="请确认密码" show-password
                                  prefix-icon="el-icon-lock"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <div style="float: right;">
                            <el-button @click="dialogFormVisible = false">取 消</el-button>
                            <el-button type="primary" @click.native.prevent="save" native-type="submit">确 定</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <!-- 		  <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false" native-type="submit">确 定</el-button>
        </div> -->
        </el-dialog>
        <!-- 底部分页 -->
        <el-pagination style="text-align: center;" class="pageList" :page-sizes="[7,9,13]" :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper" :total="counts" :current-page.sync="page"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange">
        </el-pagination>
    </div>
    </div>
</template>

<script>
    // import { showLoading, hideLoading } from '../utils/Loading.js'
    import {
        deleteFile
    } from '@/api/administrator.js'
    import {
        saveOrUpdate,
        getMemberList,
        deleteById,
        changeStatus,
        changePub,
        changeRole
    } from '@/api/user.js'
    // import axios from 'axios'
    export default {
        name: 'User',
        data() {
            return {
                loading: true,
                user: {},
                imageUrl: '',
                fileList: [],
                checkList: [],
                formLabelWidth: '80px',
                dialogFormVisible: false,
                tableData: [],
                input: '',
                counts: 0,
                page: 1,
                ids: '',
                pageSize: 7,
                id: '',
                status: '',
                dishState: '',
                rules: {
                    username: [{
                        required: true,
                        message: '请输入用户名',
                        trigger: 'blur'
                    },
                        {
                            min: 3,
                            max: 10,
                            message: '长度在 3 到 5 个字符',
                            trigger: 'blur'
                        }
                    ],
                    password: [{
                        required: true,
                        message: '请输入密码',
                        trigger: 'blur'
                    },
                        {
                            min: 1,
                            max: 20,
                            message: '长度在 1 到 20 个字符',
                            trigger: 'blur'
                        }
                    ],
                    confirmPassword: [{
                        required: true,
                        message: '请再次输入密码',
                        trigger: 'blur'
                    },
                        {
                            min: 1,
                            max: 20,
                            message: '长度在 1 到 20 个字符',
                            trigger: 'blur'
                        }
                    ],
                }
            }
        },
        created() {
            this.$store.commit('setPath', '用户管理')
            this.init()
        },
        methods: {
            async init() {
                const params = {
                    page: this.page,
                    pageSize: this.pageSize,
                    name: this.input ? this.input : ""
                }
                await getMemberList(params).then(res => {
                    this.loading = false
                    console.log(res.data.users);
                    this.tableData = res.data.users
                    this.counts = parseInt(res.data.total)
                }).catch(err => {
                    this.loading = false
                    this.$message.error('请求出错了：' + err)
                })
            }, //方法区
            formatDate(row, column) {
                // 获取单元格数据
                let data = row[column.property]
                if (data == null) {
                    return null
                }
                let dt = new Date(data)
                return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
                // + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
            },
            getImage(image) {
                return `/api/common/download?name=${image}`
            },

            handleSizeChange(val) {
                this.pageSize = val
                this.init()
            },

            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${file.name}？`);
            },
            handleRemove(file, fileList) {
                this.imageUrl = ''
                deleteFile(file.response.name).then(res => {
                    if (res.data.status == 'success') {
                        this.$message.success("移除成功！")
                        this.url = ""
                    } else if (res.data.status == 'error') {
                        this.$message.error("移除失败！")
                    }
                }).catch(err => {
                    this.$message.error("发生错误了！" + err)
                })
            },
            handleCurrentChange(val) {
                this.page = val
                this.init()
            },

            handleQuery() {
                this.page = 1;
                this.init();
            },

            // 添加
            addMemberHandle() {
                this.user = {}
                this.imageUrl = ''
                this.fileList = []
                this.dialogFormVisible = true
            },
            // changePubStatus(row){
            //     changePub(row).then(res => {
            //         if (res.data.res == '1') {
            //             this.$message.success("权限更改成功！")
            //             this.handleQuery()
            //         } else {
            //             this.$message.error("操作失败")
            //         }
            //     }).catch(erroe => {
            //         this.$message.error("发生错误了！" + error)
            //     })
            // },
            handleEdit(row) {
                if (row.avatar != '') {
                    this.imageUrl = `/gongyi/common/download?name=${row.avatar}`
                }
                this.user = JSON.parse(JSON.stringify(row))
                this.dialogFormVisible = true
            },

            handleRole(row) {
                changeRole(row).then(res => {
                    if (res.data == '1') {
                        this.$message.success("权限更改成功！")
                        this.handleQuery()
                    } else {
                        this.$message.error("操作失败")
                    }
                }).catch(erroe => {
                    this.$message.error("发生错误了！" + error)
                })
            },

            save() {
                this.$refs['userForm'].validate(async (valid) => {
                    console.log(this.user)
                    if (valid) { // 表单校验合法
                        if (this.user.password !== this.user.confirmPassword) {
                            this.$message.error("两次输入的密码不一致")
                            return false
                        }
                        await saveOrUpdate(this.user).then(res => {
                            if (JSON.stringify(res.data) == '0') {
                                this.$message.error("用户已存在！")
                            } else {
                                this.$message.success("操作成功")
                                this.dialogFormVisible = false
                                this.init()
                            }
                        }).catch(err => {
                            this.$message.error("出错了：" + err)
                        })
                    }

                })
            },

            handleAvatarSuccess(response, file, fileList) {
                // 拼接down接口预览
                // if(response.code === 0 && response.msg === '未登录'){
                //   window.top.location.href = '/backend/page/login/login.html'
                // }else{
                this.user.avatar = response.name
                this.$message.success("上传成功！")
                this.imageUrl = `/gongyi/common/download?name=${response.name}`
                // this.ruleForm.image = response.data
                // }
            },

            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },

            onChange(file) {
                if (file) {
                    const suffix = file.name.split('.')[1]
                    const size = file.size / 1024 / 1024 < 2
                    if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
                        this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
                        this.$refs.upload.clearFiles()
                        return false
                    }
                    if (!size) {
                        this.$message.error('上传文件大小不能超过 2MB!')
                        return false
                    }
                    return file
                }
            },

            // 全部操作
            handleSelectionChange(val) {
                let checkArr = []
                val.forEach((n) => {
                    checkArr.push(n.id)
                })
                console.log(val)
                this.checkList = checkArr
            },

            //状态更改
            statusHandle(row) {
                let params = {}
                if (typeof row === 'string') {
                    if (this.checkList.length === 0) {
                        this.$message.error('批量操作，请先勾选操作用户！')
                        return false
                    }
                    params.id = this.checkList.join(',')
                    params.status = row
                } else {
                    params.id = row.id
                    params.status = row.status ? '0' : '1'
                }
                this.dishState = params
                this.$confirm('确认更改该用户状态?', '提示', {
                    'confirmButtonText': '确定',
                    'cancelButtonText': '取消',
                    'type': 'warning'
                }).then(() => {
                    // 起售停售---批量起售停售接口
                    changeStatus(this.dishState).then(res => {
                        console.log(res.data.code)
                        if (res.data.code == 1) {
                            this.$message.success('用户状态已经更改成功！')
                            this.handleQuery()
                        } else {
                            this.$message.error(res.msg || '操作失败')
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                })
            },

            // 删除
            deleteHandle(type, id) {
                console.log(id)
                if (type === '批量' && id === null) {
                    if (this.checkList.length === 0) {
                        return this.$message.error('请选择删除对象')
                    }
                }
                this.$confirm('确认删除该用户, 是否继续?', '确定删除', {
                    'confirmButtonText': '确定',
                    'cancelButtonText': '取消',
                }).then(() => {
                    deleteById(type === '批量' ? this.checkList.join(',') : id).then(res => {
                        if (res.data == '1') {
                            this.$message.success('删除成功！')
                            this.handleQuery()
                        } else {
                            this.$message.error('操作失败')
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                })
            },
        }
    }
</script>

<style>
    .dashboard-container .container .tableBox {
        width: 100%;
        border: solid 2px #f3f4f7;
        border-radius: 2px;
    }

    .el-link {
        margin-left: 15px;
    }

    .delBut {
        color: #f56c6c !important;
        position: relative;
    }

    .common::after {
        content: "";
        position: absolute;
        right: -6px;
        height: 14px;
        width: 0px;
        border-right: solid 1px #d1d3d9 !important;
    }
</style>
